package com.gcit.seniorWish.web.modular.examinee.controller;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.gcit.seniorWish.core.base.controller.BaseController;
import com.gcit.seniorWish.core.base.tips.Tip;
import com.gcit.seniorWish.core.exception.GunsException;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.gcit.seniorWish.web.common.constant.enums.SystemConfigurateEnum;
import com.gcit.seniorWish.web.common.persistence.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gcit.seniorWish.web.common.constant.enums.ExamineeStatusEnum;
import com.gcit.seniorWish.web.common.constant.enums.StatisticsReportEnum;
import com.gcit.seniorWish.web.common.constant.enums.UserTypeEnum;
import com.gcit.seniorWish.web.common.constant.factory.ConstantFactory;
import com.gcit.seniorWish.web.common.constant.factory.PageFactory;
import com.gcit.seniorWish.web.core.exception.BizExceptionEnum;
import com.gcit.seniorWish.web.core.shiro.ShiroKit;
import com.gcit.seniorWish.web.modular.examinee.service.ISeniorExamineeService;
import com.gcit.seniorWish.web.modular.examinee.service.ISeniorSchoolClassService;
import com.gcit.seniorWish.web.modular.examinee.service.ISeniorSchoolService;
import com.gcit.seniorWish.web.modular.examinee.warpper.SeniorWishWarpper;
import com.gcit.seniorWish.web.modular.portal.service.ISeniorWishService;
import com.gcit.seniorWish.web.modular.report.service.ISeniorStatisticsReportService;
import com.gcit.seniorWish.web.modular.report.warpper.StatisticsReportWarpper;
import com.gcit.seniorWish.web.modular.system.service.IUserMgrService;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.StrUtil;

/**
 * 考生填报,打印 统计 上报 相关控制器
 *
 * @author tonglu
 * @Date 2018-03-20 10:52:55
 */
@Controller
@RequestMapping("/seniorWish")
public class SeniorWishController extends BaseController {

	private String PREFIX = "/seniorwish";

	@Autowired
	private ISeniorExamineeService seniorExamineeService;

	@Autowired
	private ISeniorSchoolClassService seniorSchoolClassService;

	@Autowired
	ISeniorSchoolService seniorSchoolService;

	@Autowired
	private IUserMgrService userMgrService;

	@Autowired
	private ISeniorStatisticsReportService seniorStatisticsReportService;

	@Autowired
	private ISeniorWishService seniorWishService;

	/**
	 * 考生填报数据列表
	 */
	@RequestMapping("/examinee")
	public String examinee(Model model) {
		if (UserTypeEnum.TEACHING.getValue() == ShiroKit.getUser().getType()) {// 登录人为班主任
			model.addAttribute("schoolu",
					seniorSchoolService.listSchoolForSelect2(null, ShiroKit.getUser().getSchoolId()));
			model.addAttribute("classu", seniorSchoolClassService.listSchoolClassForSelect2(null,
					ShiroKit.getUser().getSchoolId(), ShiroKit.getUser().getClassId()));
		} else if (UserTypeEnum.SCHOOL.getValue() == ShiroKit.getUser().getType()) {// 登录人为学校管理员
			model.addAttribute("schoolu",
					seniorSchoolService.listSchoolForSelect2(null, ShiroKit.getUser().getSchoolId()));
			model.addAttribute("classu", null);
		} else {
			model.addAttribute("schoolu", null);
			model.addAttribute("classu", null);
		}
		return PREFIX + "/examinee.html";
	}

	/**
	 * 获取考生填报列表
	 */
	@SuppressWarnings({"unchecked", "rawtypes"})
	@RequestMapping(value = "/examineeList")
	@ResponseBody
	public Object examineeList(@RequestParam(required = false) String seniorSchoolId,
	                           @RequestParam(required = false) String seniorClassId, @RequestParam(required = false) String examCardNumber,
	                           @RequestParam(required = false) String confirmStatus) {
		Page<Map<String, Object>> page = new PageFactory().defaultPage();
		if (UserTypeEnum.TEACHING.getValue() == ShiroKit.getUser().getType()) {// 登录人为班主任
			seniorSchoolId = ShiroKit.getUser().getSchoolId();
			seniorClassId = ShiroKit.getUser().getClassId();
		} else if (UserTypeEnum.SCHOOL.getValue() == ShiroKit.getUser().getType()) {// 登录人为学校管理员
			seniorSchoolId = ShiroKit.getUser().getSchoolId();
		}
		page.setRecords((List<Map<String, Object>>) new SeniorWishWarpper(
				seniorExamineeService.getExaminees(page, seniorSchoolId, seniorClassId, examCardNumber, confirmStatus))
				.warp());
		return packForBT(page);
	}

	/**
	 * 考生填报详情
	 */
	@RequestMapping("/examineeItem")
	public String examineeItem(String id, Model model) {
		// 根据学生的准考证号查询出考生信息
		SeniorExaminee examinee = seniorExamineeService.selectById(id);
		examinee.setSeniorSchoolName(
				ConstantFactory.me().getSeniorSchoolById(examinee.getSeniorSchoolId()).getSchoolName());
		examinee.setSeniorClassName(ConstantFactory.me().getSeniorSchoolClassById(examinee.getSeniorClassId()).getSenoirClassName());
		try {
			model.addAttribute("seniorWish", seniorWishService.seniorWishDetail(examinee.getExamCardNumber()));
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		model.addAttribute("examinee", examinee);
		return PREFIX + "/examineeItem.html";
	}

	/**
	 * 重置登录密码
	 *
	 * @param examineeId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/changePwd")
	@ResponseBody
	public Object changePwd(String examineeId) {
		if (!StrUtil.isBlank(examineeId)) {
			SeniorExaminee seniorExaminee = seniorExamineeService.selectById(examineeId);
			User user = userMgrService
					.selectOne(Condition.create().eq("account", seniorExaminee.getExamCardNumber()));
			user.setSalt(ShiroKit.getRandomSalt(5));
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			user.setPassword(ShiroKit.md5(sdf.format(seniorExaminee.getBirthday()), user.getSalt()));
			userMgrService.updateById(user);
		}
		return SUCCESS_TIP;
	}

	/**
	 * 重置志愿状态
	 *
	 * @param examineeId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/changeSatus")
	@ResponseBody
	public Object changeSatus(String examineeId) throws ParseException {
		//查询填报结束时间，如果当前时间大于填报结束时间，不能重置填报状态
		SystemConfigurate configurate = ConstantFactory.me().getSystemConfigurateByKey(SystemConfigurateEnum.SENIOR_WISH_END_DATE.getMessage());
		if (configurate != null) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH");
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日HH点");
			Date wishEndDate = sdf.parse(configurate.getConfigurateValue() + ":00:00");
			// 判断当前时间是否大于截止时间
			if ((new Date().getTime() - wishEndDate.getTime()) > 0) {// 大于不能登录填报系统
				throw new GunsException(BizExceptionEnum.PORTAL_HAS_CLOSED);
			}
		}
		if (!StrUtil.isBlank(examineeId)) {
			//查询学生
			SeniorExaminee seniorExaminee = seniorExamineeService.selectOne(Condition.create().eq("id", examineeId));
			if (seniorExaminee != null) {
				//查询学生所在的班级是否已经完成上报，如果完成上报，不能再重置状态
				if (seniorStatisticsReportService.selectCount(Condition.create().eq("senior_class_id", seniorExaminee.getSeniorClassId())) > 0) {
					throw new GunsException(BizExceptionEnum.EXAMINEE_CLASS_REPORTED);
				}
				// 不修改已填报状态
				// seniorExaminee.setWriteStatus(ExamineeStatusEnum.NOT_YET_WRITE.getValue());
				seniorExaminee.setConfirmStatus(ExamineeStatusEnum.NOT_YET_CONFIRM.getValue());
				seniorExamineeService.updateExaminee(seniorExaminee);
				/*
				不再修改上报状态，只有所在班级未上报的学生才可以重置状态
				// 修改上报状态
				SeniorStatisticsReport classReport = seniorStatisticsReportService
						.selectOne(Condition.create().eq("senior_class_id", seniorExaminee.getSeniorClassId()));
				SeniorStatisticsReport schoolReport = seniorStatisticsReportService.selectOne(Condition.create()
						.eq("senior_school_id", seniorExaminee.getSeniorSchoolId()).isNull("senior_class_id"));
				if (classReport != null) {
					classReport.setStatus(StatisticsReportEnum.REPORTNO.getValue());
					List<Map<String, Object>> list = seniorStatisticsReportService.getStatistics(null,
							seniorExaminee.getSeniorClassId());
					if (list.size() > 0) {
						classReport = getSeniorStatisticsReport(classReport, list);
					}
					seniorStatisticsReportService.updateById(classReport);
				}
				if (schoolReport != null) {
					schoolReport.setStatus(StatisticsReportEnum.REPORTNO.getValue());
					List<Map<String, Object>> list = seniorStatisticsReportService
							.getStatistics(seniorExaminee.getSeniorSchoolId(), null);
					if (list.size() > 0) {
						schoolReport = getSeniorStatisticsReport(schoolReport, list);
					}
					seniorStatisticsReportService.updateById(schoolReport);
				}*/
			}
		}
		return SUCCESS_TIP;
	}

	/**
	 * 打印志愿预览
	 */
	@RequestMapping("/printWish")
	public String printWish(String examineeIds, Model model) {
		if (UserTypeEnum.TEACHING.getValue() == ShiroKit.getUser().getType()) {// 登录人为班主任
			model.addAttribute("schoolu",
					seniorSchoolService.listSchoolForSelect2(null, ShiroKit.getUser().getSchoolId()));
			model.addAttribute("classu", seniorSchoolClassService.listSchoolClassForSelect2(null,
					ShiroKit.getUser().getSchoolId(), ShiroKit.getUser().getClassId()));
		} else if (UserTypeEnum.SCHOOL.getValue() == ShiroKit.getUser().getType()) {// 登录人为学校管理员
			model.addAttribute("schoolu",
					seniorSchoolService.listSchoolForSelect2(null, ShiroKit.getUser().getSchoolId()));
			model.addAttribute("classu", null);
		} else {
			model.addAttribute("schoolu", null);
			model.addAttribute("classu", null);
		}

		return PREFIX + "/printWish.html";
	}

	/**
	 * 打印志愿预览
	 */
	@RequestMapping("/printWishPreview")
	public String printWishPreview(String examineeIds, Model model) {
		if (StrUtil.isBlank(examineeIds)) {
			throw new GunsException(BizExceptionEnum.REQUEST_NULL);
		}
		List<String> examineeIdList = Arrays.asList(examineeIds.split(","));
		if (examineeIdList.size() <= 0) {
			throw new GunsException(BizExceptionEnum.REQUEST_NULL);
		}
		model.addAttribute("examineeList", seniorWishService.listSeniorExamineeWithSeniorWish(examineeIdList));
		return PREFIX + "/printWishPreview.html";
	}

	/**
	 * 获取打印志愿列表
	 */
	@SuppressWarnings({"unchecked", "rawtypes"})
	@RequestMapping(value = "/printWishList")
	@ResponseBody
	public Object printWishList(@RequestParam(required = false) String seniorSchoolId,
	                            @RequestParam(required = false) String seniorClassId, @RequestParam(required = false) String examCardNumber,
	                            @RequestParam(required = false) String confirmStatus) {
		Page<Map<String, Object>> page = new PageFactory().defaultPage();
		if (UserTypeEnum.TEACHING.getValue() == ShiroKit.getUser().getType()) {// 登录人为班主任
			seniorSchoolId = ShiroKit.getUser().getSchoolId();
			seniorClassId = ShiroKit.getUser().getClassId();
		} else if (UserTypeEnum.SCHOOL.getValue() == ShiroKit.getUser().getType()) {// 登录人为学校管理员
			seniorSchoolId = ShiroKit.getUser().getSchoolId();
		}
		page.setRecords((List<Map<String, Object>>) new SeniorWishWarpper(
				seniorExamineeService.getExaminees(page, seniorSchoolId, seniorClassId, examCardNumber, confirmStatus))
				.warp());
		return packForBT(page);
	}

	/**
	 * 志愿统计数据列表
	 */
	@RequestMapping("/statReport")
	public String statReport(Model model) {
		if (UserTypeEnum.TEACHING.getValue() == ShiroKit.getUser().getType()) {// 登录人为班主任
			model.addAttribute("schoolu",
					seniorSchoolService.listSchoolForSelect2(null, ShiroKit.getUser().getSchoolId()));
			model.addAttribute("classu", seniorSchoolClassService.listSchoolClassForSelect2(null,
					ShiroKit.getUser().getSchoolId(), ShiroKit.getUser().getClassId()));
		} else if (UserTypeEnum.SCHOOL.getValue() == ShiroKit.getUser().getType()) {// 登录人为学校管理员
			model.addAttribute("schoolu",
					seniorSchoolService.listSchoolForSelect2(null, ShiroKit.getUser().getSchoolId()));
			model.addAttribute("classu", null);
		} else {
			model.addAttribute("schoolu", null);
			model.addAttribute("classu", null);
		}
		return PREFIX + "/statReport.html";
	}

	/**
	 * 获取志愿统计列表
	 */
	@SuppressWarnings({"unchecked", "rawtypes"})
	@RequestMapping(value = "/statReportList")
	@ResponseBody
	public Object statReportList(@RequestParam(required = false) String seniorSchoolId,
	                             @RequestParam(required = false) String seniorClassId) {
		Page<Map<String, Object>> page = new PageFactory().defaultPage();
		if (UserTypeEnum.TEACHING.getValue() == ShiroKit.getUser().getType()) {// 登录人为班主任
			seniorSchoolId = ShiroKit.getUser().getSchoolId();
			seniorClassId = ShiroKit.getUser().getClassId();
		} else if (UserTypeEnum.SCHOOL.getValue() == ShiroKit.getUser().getType()) {// 登录人为学校管理员
			seniorSchoolId = ShiroKit.getUser().getSchoolId();
		}
		page.setRecords(seniorStatisticsReportService.getStatistics(page, seniorSchoolId, seniorClassId));
		return packForBT(page);
	}

	/**
	 * 上报
	 */
	@SuppressWarnings({"unchecked"})
	@RequestMapping(value = "/report")
	@ResponseBody
	public Tip report() {
		Wrapper con = Condition.create().eq("senior_school_id", ShiroKit.getUser().getSchoolId());
		if (StrUtil.isNotBlank(ShiroKit.getUser().getClassId())) {
			con.eq("senior_class_id", ShiroKit.getUser().getClassId());
		} else {
			con.isNull("senior_class_id");
		}
		//判断是否已经上报过
		if (seniorStatisticsReportService.selectCount(con) > 0) {
			throw new GunsException(BizExceptionEnum.REPORT_EXIST);
		}
		SeniorStatisticsReport report = new SeniorStatisticsReport();// 要插入的上报数据
		if (UserTypeEnum.TEACHING.getValue() == ShiroKit.getUser().getType()) {// 登录人为班主任
			//判断是否所有考生都确认志愿
			int count = seniorExamineeService
					.selectCount(Condition.create().eq("senior_class_id", ShiroKit.getUser().getClassId())
							.eq("confirm_status", ExamineeStatusEnum.NOT_YET_CONFIRM.getValue()));
			if (count > 0) {// 表示考生还有未确认的志愿
				throw new GunsException(BizExceptionEnum.EXAMINEE_NO_CONFIRM);
			} else {
				report.setStatus(StatisticsReportEnum.REPORTYES.getValue());
			}
			//查询班级的统计数据
			List<Map<String, Object>> list = seniorStatisticsReportService.getStatistics(null, ShiroKit.getUser().getClassId());
			if (list.size() > 0) {
				report = getSeniorStatisticsReport(report, list);
				report.setSeniorClassId(ShiroKit.getUser().getClassId());
				report.setSeniorSchoolId(ShiroKit.getUser().getSchoolId());
			}
		} else if (UserTypeEnum.SCHOOL.getValue() == ShiroKit.getUser().getType()) {// 登录人为学校管理员
//			//判断是否还有学生未确认志愿
//			if (seniorExamineeService.selectCount(Condition.create()
//					.eq("senior_school_id", ShiroKit.getUser().getSchoolId())
//					.eq("confirm_status", ExamineeStatusEnum.NOT_YET_CONFIRM.getValue())) > 0) {
//				throw new GunsException(BizExceptionEnum.CLASS_NO_CONFIRM);
//			} else {
//				report.setStatus(StatisticsReportEnum.REPORTYES.getValue());
//			}
			//当上报数据中该学校的班级上报数量小于班级
			if (seniorStatisticsReportService.selectCount(Condition.create()
					.eq("senior_school_id", ShiroKit.getUser().getSchoolId()).isNotNull("senior_class_id"))
					< seniorSchoolClassService.selectCount(Condition.create()
					.eq("senoir_school_id", ShiroKit.getUser().getSchoolId()))) {
				throw new GunsException(BizExceptionEnum.CLASS_NO_CONFIRM);
			}
			report.setStatus(StatisticsReportEnum.REPORTYES.getValue());
			//查询学校统计数据
			List<Map<String, Object>> list = seniorStatisticsReportService
					.getStatistics(ShiroKit.getUser().getSchoolId(), null);
			if (list.size() > 0) {
				report = getSeniorStatisticsReport(report, list);
				report.setSeniorSchoolId(ShiroKit.getUser().getSchoolId());
			}
		}
		seniorStatisticsReportService.insert(report);
		return SUCCESS_TIP;
	}

	private SeniorStatisticsReport getSeniorStatisticsReport(SeniorStatisticsReport report, List<Map<String, Object>> list) {
		Integer examineeNum = 0;
		Integer nowriteNum = 0;
		Integer thenwriteNum = 0;
		Integer abandonedNum = 0;
		Integer noconfirmNum = 0;
		Integer thenconfirmNum = 0;
		for (Map<String, Object> map : list) {
			examineeNum += Integer.valueOf(map.get("examineeNum") + "");
			nowriteNum += Integer.valueOf(map.get("nowriteNum") + "");
			thenwriteNum += Integer.valueOf(map.get("thenwriteNum") + "");
			abandonedNum += Integer.valueOf(map.get("abandonedNum") + "");
			noconfirmNum += Integer.valueOf(map.get("noconfirmNum") + "");
			thenconfirmNum += Integer.valueOf(map.get("thenconfirmNum") + "");
		}
		report.setExamineeNum(examineeNum);
		report.setNowriteNum(nowriteNum);
		report.setThenwriteNum(thenwriteNum);
		report.setAbandonedNum(abandonedNum);
		report.setNoconfirmNum(noconfirmNum);
		report.setThenconfirmNum(thenconfirmNum);
		return report;
	}

	/**
	 * 查看上报数据列表
	 */
	@RequestMapping("/lookReport")
	public String lookReport(Model model) {
		String url = PREFIX + "/lookClassReport.html";
		if (UserTypeEnum.TEACHING.getValue() == ShiroKit.getUser().getType()) {// 登录人为班主任
			model.addAttribute("schoolu",
					seniorSchoolService.listSchoolForSelect2(null, ShiroKit.getUser().getSchoolId()));
			model.addAttribute("classu", seniorSchoolClassService.listSchoolClassForSelect2(null,
					ShiroKit.getUser().getSchoolId(), ShiroKit.getUser().getClassId()));
		} else if (UserTypeEnum.SCHOOL.getValue() == ShiroKit.getUser().getType()) {// 登录人为学校管理员
			model.addAttribute("schoolu",
					seniorSchoolService.listSchoolForSelect2(null, ShiroKit.getUser().getSchoolId()));
			model.addAttribute("classu", seniorSchoolClassService.listSchoolClassForSelect2(null,
					ShiroKit.getUser().getSchoolId(), null));
		} else {
			model.addAttribute("schoolu", null);
			model.addAttribute("classu", null);
			url = PREFIX + "/lookSchoolReport.html";
		}
		return url;
	}

	/**
	 * 获取查看上报列表
	 */
	@SuppressWarnings({"unchecked", "rawtypes"})
	@RequestMapping(value = "/lookReportList")
	@ResponseBody
	public Object lookReportList(@RequestParam(required = false) String seniorSchoolId,
	                             @RequestParam(required = false) String seniorClassId) {
		EntityWrapper<SeniorStatisticsReport> ew = new EntityWrapper<SeniorStatisticsReport>();
		Page<Map<String, Object>> page = new PageFactory().defaultPage();
		if (UserTypeEnum.TEACHING.getValue() == ShiroKit.getUser().getType()) {// 登录人为班主任
			ew.isNotNull("senior_class_id");
			seniorSchoolId = ShiroKit.getUser().getSchoolId();
			seniorClassId = ShiroKit.getUser().getClassId();
		} else if (UserTypeEnum.SCHOOL.getValue() == ShiroKit.getUser().getType()) {// 登录人为学校管理员
			ew.isNotNull("senior_class_id");
			seniorSchoolId = ShiroKit.getUser().getSchoolId();
		} else {//管理员
			ew.isNull("senior_class_id");
		}
		if (StrUtil.isNotBlank(seniorSchoolId))
			ew.eq("senior_school_id", seniorSchoolId);
		if (StrUtil.isNotBlank(seniorClassId))
			ew.eq("senior_class_id", seniorClassId);
		seniorStatisticsReportService.selectMapsPage(page, ew);
		page.setRecords((List<Map<String, Object>>) new StatisticsReportWarpper(page.getRecords()).warp());
		return packForBT(page);
	}

}
